package com.qumoyugo.springframework.core.convert.converter;

import cn.hutool.core.lang.Assert;

import java.util.Set;

/**
 * 通用的转换器
 */
public interface GenericConverter {

    /**
     * 返回此转换器可以支持转换的源类型和目标类型
     * @return {@link ConvertiblePair}
     */
    Set<ConvertiblePair> getConvertibleTypes();

    /**
     * 返回转换后的对象
     * @param source 源对象
     * @param sourceType 源类型
     * @param targetType 目标类型
     * @return 转换后的对象
     */
    Object convert(Object source, Class sourceType, Class targetType);

    final class ConvertiblePair {
        private Class<?> sourceType;
        private Class<?> targetType;

        public ConvertiblePair(Class<?> sourceType, Class<?> targetType) {
            Assert.notNull(sourceType, "Source type must not be null");
            Assert.notNull(targetType, "Target type must not be null");
            this.sourceType = sourceType;
            this.targetType = targetType;
        }

        public Class<?> getSourceType() {
            return sourceType;
        }

        public Class<?> getTargetType() {
            return targetType;
        }

        @Override
        public int hashCode() {
            return this.sourceType.hashCode()*31 + this.targetType.hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null || obj.getClass() != this.getClass()) {
                return false;
            }
            ConvertiblePair other = (ConvertiblePair) obj;
            return this.sourceType.equals(other.sourceType) && this.targetType.equals(other.targetType);
        }
    }
}
